package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.bookmarks.Languageapp_Bookmarks;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.discover.word.Maori_Discover_Word;
import com.maori.languageapp.discover.word.Maori_Discover_Word_Details;
import com.maori.languageapp.discover.word.Maori_Discover_Word_Details.loadSingleView;
//import com.maori.languageapp.discover.Maori_Discover_Word_Details;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.model.Maori_NavDrawerItem;
import com.maori.languageapp.service.Maori_Loading_Splash;
import com.maori.languageapp.subview.Maori_BookMark_Items;
import com.maori.languageapp.userprofile.Maori_Display_User_Profile;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_MainActivity extends FragmentActivity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;
	TextView profile_text, profile_text_name;
	String SYNCACTIVE = "0";

	ProgressDialog mProgressDialog;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String mainUrl;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	JSONArray jArray;
	ImageView camera_button,profile_image;
	private SQLiteDatabase mydb;
	String UserArray, LanguageArray, CategoryArray, DialectArray, MediaArray,
			ContentTypeArray, WordsArray;
	String useremail, userrole, userMID, lastname ,CurrentUID;
	String MyRecordsCount = "0",MyBookMarkCount = "0";
	String LastDownloadUpdateTime = "2014-01-01 12:00:00";
	
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private Uri fileUri;
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";
	static String upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
	static String filename = "404";
	static String sourceUrl;
	
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";
	private String IDIOM_TABLE = "Idiom";
	String UID;
	private Dialog mSplashDialog;

	String desDirectoryImage = "http://langapp.mirzabros.com/lanappimage/";

	public void displayProfile(View view) {
		Intent intent = new Intent(getBaseContext(), Maori_Display_User_Profile.class);
		this.startActivity(intent);
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			SYNCACTIVE = extras.getString("SYNC");
			if (SYNCACTIVE.equals("ACTIVE")) {
				new DownloadLanguageDetails().execute();
			}
		}

		// Get Current User Details
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curGetUserInfo = null;
		String queryGetUserInfo;
		try {
			queryGetUserInfo = "SELECT * FROM User Where Activate = '1'";
			curGetUserInfo = mydb.rawQuery(queryGetUserInfo, null);
			if (curGetUserInfo != null) {
				if (curGetUserInfo.getCount() > 0) {
					while (curGetUserInfo.moveToNext()) {
						useremail = curGetUserInfo.getString(4);
						lastname = curGetUserInfo.getString(2);
						userrole = curGetUserInfo.getString(7);
						userMID = curGetUserInfo.getString(12);
						CurrentUID = curGetUserInfo.getString(11);
						
						MyRecordsCount = curGetUserInfo.getString(17);
						MyBookMarkCount = curGetUserInfo.getString(16);

						Log.v("TAG", "MyRecordsCount  : " + MyRecordsCount);
						Log.v("TAG", "MyBookMarkCount   : " + MyBookMarkCount);
					}
				}
			}

		} catch (Exception e) {

		}
		mydb.close();

		mTitle = mDrawerTitle = getTitle();

		navMenuTitles = getResources().getStringArray(
				R.array.maori_nav_drawer_items);
		navMenuIcons = getResources().obtainTypedArray(
				R.array.maori_nav_drawer_icons);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

		// PSJ - Adding Profile Picture
		View header = getLayoutInflater().inflate(
				R.layout.maori_profile_header, null);
		mDrawerList.addHeaderView(header);

		profile_text = (TextView) findViewById(R.id.profile_text);
		profile_text_name = (TextView) findViewById(R.id.profile_text_name);
		profile_text.setText(useremail + "(" + userrole + ")");
		profile_text_name.setText(lastname);
		camera_button = (ImageView) findViewById(R.id.camera_button);
		profile_image = (ImageView) findViewById(R.id.profile_image);
		// Create an object for subclass of AsyncTask
		GetXMLTask task = new GetXMLTask();
		// Execute the task
		task.execute(new String[] { userMID });

		// profile_text.setText("Eranda");
		navDrawerItems = new ArrayList<Maori_NavDrawerItem>();

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[0],
				navMenuIcons.getResourceId(0, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[1],
				navMenuIcons.getResourceId(1, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[2],
				navMenuIcons.getResourceId(2, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[3],
				navMenuIcons.getResourceId(3, -1), true, MyRecordsCount));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[4],
				navMenuIcons.getResourceId(4, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[5],
				navMenuIcons.getResourceId(5, -1), true, MyBookMarkCount));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[6],
				navMenuIcons.getResourceId(6, -1)));
		
		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[7],
				navMenuIcons.getResourceId(7, -1)));

		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		adapter = new Maori_NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			// Show the Up button in the action bar.
			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar().setHomeButtonEnabled(true);
			getActionBar().setBackgroundDrawable(
					new ColorDrawable(Color.parseColor("#0d284c")));
		}

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menubutton, R.string.app_name, R.string.app_name) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			displayView(0);
		}
		
		
		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
						ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});
	}

	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 1:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 2:
			fragment = new Maori_Main_Fragment(1);
			break;
		case 3:
			fragment = new Maori_Main_Fragment(2);
			break;
		case 4:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 5:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 6:
			Intent intentBookMark = new Intent(getBaseContext(), Languageapp_Bookmarks.class);
			this.startActivity(intentBookMark);
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			break;
		case 7:
			Intent intent = new Intent(getBaseContext(), Maori_Display_User_Profile.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
			break;
			
		case 8:
			fragment = new Maori_Main_Fragment(8);
			break;

		default:
			break;
		}

		if (fragment != null) {

			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);

		} else {
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	// Download available details
	private class DownloadLanguageDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_MainActivity.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Downloading....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			// *****Download and Update Language Details*****
			ArrayList<NameValuePair> nameValuePairsLanguage = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);

				HttpPost httppost = new HttpPost(UrlContant.LanguageURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsLanguage));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				LanguageArray = sb.toString();

				jArray = new JSONArray(LanguageArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String LID = json_data.getString("LID");
					String Language = json_data.getString("Language");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(LANGUAGE_TABLE, null,
								"LID ='" + LID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Language");
						} else {
							enterLanguageInfo.put("LID", LID.trim());
							enterLanguageInfo.put("Language", Language.trim());
							mydb.insert(LANGUAGE_TABLE, null, enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Language Download Complete------

			// *****Download and Update Category Details*****
			ArrayList<NameValuePair> nameValuePairsCategory = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.CategoryURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsCategory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				CategoryArray = sb.toString();

				jArray = new JSONArray(CategoryArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String node_category = json_data.getString("node_category");
					String NCMID = json_data.getString("NCMID");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(NODECATEGORY_TABLE,
								null, "NCMID ='" + NCMID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Category");
						} else {
							enterLanguageInfo.put("node_cat_id", NCMID.trim());
							enterLanguageInfo.put("node_category",
									node_category.trim());
							enterLanguageInfo.put("NCMID", NCMID.trim());
							mydb.insert(NODECATEGORY_TABLE, null,
									enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Category Download Complete------

			// *****Download and Update Dialect Details*****
			ArrayList<NameValuePair> nameValuePairsDialect = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.DialectURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsDialect));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				DialectArray = sb.toString();

				jArray = new JSONArray(DialectArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String dialact_id = json_data.getString("dialact_id");
					String dialact = json_data.getString("dialact");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterDialectInfo = new ContentValues();
					// Check Previous Language
					Cursor readDialectDetails = null;
					try {
						readDialectDetails = mydb.query(DIALACT_TABLE, null,
								"dialact_id ='" + dialact_id.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (readDialectDetails != null) {
						if (readDialectDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Dialect");
						} else {
							enterDialectInfo.put("dialact_id",
									dialact_id.trim());
							enterDialectInfo.put("dialact", dialact.trim());
							mydb.insert(DIALACT_TABLE, null, enterDialectInfo);
							readDialectDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Dialect Download Complete------

			// *****Download and Update Media Details*****
			ArrayList<NameValuePair> nameValuePairsMedia = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.MediaURL);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsMedia));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				MediaArray = sb.toString();

				jArray = new JSONArray(MediaArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String MID = json_data.getString("MID");
					String media_type = json_data.getString("media_type");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterMediaInfo = new ContentValues();
					// Check Previous Language
					Cursor readMediaDetails = null;
					try {
						readMediaDetails = mydb.query(MEDIA_TABLE, null,
								"MID ='" + MID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readMediaDetails != null) {
						if (readMediaDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Media");
						} else {
							enterMediaInfo.put("MID", MID.trim());
							enterMediaInfo.put("media_type", media_type.trim());
							mydb.insert(MEDIA_TABLE, null, enterMediaInfo);
							readMediaDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Dialect Download Complete------

			// *****Download and Update Content Type Details*****
			ArrayList<NameValuePair> nameValuePairsContentType = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.ContentTypeURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsContentType));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				ContentTypeArray = sb.toString();

				jArray = new JSONArray(ContentTypeArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String content_type_id = json_data
							.getString("content_type_id");
					String content = json_data.getString("content");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterContentTypeInfo = new ContentValues();
					// Check Previous Language
					Cursor readContentTypeDetails = null;
					try {
						readContentTypeDetails = mydb.query(CONTENTTYPE_TABLE,
								null,
								"content_type_id ='" + content_type_id.trim()
										+ "'", null, null, null, null);
					} catch (Exception e) {
					}
					if (readContentTypeDetails != null) {
						if (readContentTypeDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Content Type");
						} else {
							enterContentTypeInfo.put("content_type_id",
									content_type_id.trim());
							enterContentTypeInfo.put("content", content.trim());
							mydb.insert(CONTENTTYPE_TABLE, null,
									enterContentTypeInfo);
							readContentTypeDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Content Type Download Complete------

			// *****Download and Update Words Details*****

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.WordsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE WORDS :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String WordID = json_data.getString("WordID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String word = json_data.getString("word");
					String otherwords = json_data.getString("otherwords");
					String activeState = json_data.getString("node_active_a");
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(WORD_TABLE, null,
								"WordID ='" + WordID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("WordID", WordID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("word", word.trim());
							wordsUpdate.put("otherwords", otherwords.trim());
							wordsUpdate.put("activeState", activeState.trim());
							
							mydb.update(WORD_TABLE, wordsUpdate, "WordID ='"
									+ WordID.trim() + "'", null);
						} else {
							enterWordInfo.put("WordID", WordID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("word", word.trim());
							enterWordInfo.put("Otherwords", otherwords.trim());
							enterWordInfo.put("activeState", activeState.trim());
							mydb.insert(WORD_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Idiom Details*****

			ArrayList<NameValuePair> nameValuePairsIdiom = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.IdiomURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST IDIOM :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsIdiom));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();

				Log.e("RESPONSE Idiom :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String IdiomID = json_data.getString("IdiomID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String Idiom = json_data.getString("Idiom");
					String Otheridioms = json_data.getString("Otheridioms");
					String activeState = json_data.getString("$node_active_a");
					
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(IDIOM_TABLE, null,
								"IdiomID ='" + IdiomID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("IdiomID", IdiomID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Idiom", Idiom.trim());
							wordsUpdate.put("Otheridioms", Otheridioms.trim());
							wordsUpdate.put("activeState", activeState.trim());
							mydb.update(IDIOM_TABLE, wordsUpdate, "WordID ='"
									+ IdiomID.trim() + "'", null);
						} else {
							enterWordInfo.put("IdiomID", IdiomID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Idiom", Idiom.trim());
							enterWordInfo.put("Otheridioms", Otheridioms.trim());
							enterWordInfo.put("activeState", activeState.trim());
							mydb.insert(IDIOM_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Songs Details*****

			ArrayList<NameValuePair> nameValuePairsSongs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.SongsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST SONGS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsSongs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Songs :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String SongID = json_data.getString("SongID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String song_title = json_data.getString("song_title");
					String song_content = json_data.getString("song_content");
					String other_song_title = json_data
							.getString("other_song_title");
					String other_song_content = json_data
							.getString("other_song_content");
					String activeState = json_data
							.getString("node_active_a");
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(SONG_TABLE, null,
								"SongID ='" + SongID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Song");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("SongID", SongID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("song_title", song_title.trim());
							wordsUpdate
									.put("song_content", song_content.trim());
							wordsUpdate.put("other_song_title",
									other_song_title.trim());
							wordsUpdate.put("other_song_content",
									other_song_content.trim());
							wordsUpdate.put("activeState", activeState.trim());
							mydb.update(SONG_TABLE, wordsUpdate, "SongID ='"
									+ SongID.trim() + "'", null);
						} else {
							enterWordInfo.put("SongID", SongID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("song_title", song_title.trim());
							enterWordInfo.put("song_content",
									song_content.trim());
							enterWordInfo.put("other_song_title",
									other_song_title.trim());
							enterWordInfo.put("other_song_content",
									other_song_content.trim());
							enterWordInfo.put("activeState", activeState.trim());
							mydb.insert(SONG_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Phrase Details*****

			ArrayList<NameValuePair> nameValuePairsPhrase = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.PhraseURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsPhrase));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Phrase :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String PhraseID = json_data.getString("PhraseID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String Phrase = json_data.getString("Phrase");
					String OtherPhrase = json_data.getString("OtherPhrase");
					String activeState = json_data.getString("node_active_a");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(PHRASE_TABLE, null,
								"PhraseID ='" + PhraseID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Phrase");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("PhraseID", PhraseID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Phrase", Phrase.trim());
							wordsUpdate.put("OtherPhrase", OtherPhrase.trim());
							wordsUpdate.put("activeState", activeState.trim());
							
							mydb.update(PHRASE_TABLE, wordsUpdate,
									"PhraseID ='" + PhraseID.trim() + "'", null);
						} else {
							enterWordInfo.put("PhraseID", PhraseID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Phrase", Phrase.trim());
							enterWordInfo
									.put("OtherPhrase", OtherPhrase.trim());
							enterWordInfo.put("activeState", activeState.trim());
							
							mydb.insert(PHRASE_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Story Details*****

			ArrayList<NameValuePair> nameValuePairsStory = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.StoryURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsStory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE STORY :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String StoryID = json_data.getString("StoryID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String story_title = json_data.getString("story_title");
					String story_content = json_data.getString("story_content");
					String other_story_title = json_data
							.getString("other_story_title");
					String other_story_content = json_data
							.getString("other_story_content");
					String activeState = json_data.getString("node_active_a");
					
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(STORY_TABLE, null,
								"StoryID ='" + StoryID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting StoryID");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("StoryID", StoryID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("story_title", story_title.trim());
							wordsUpdate.put("story_content",
									story_content.trim());
							wordsUpdate.put("other_story_title",
									other_story_title.trim());
							wordsUpdate.put("other_story_content",
									other_story_content.trim());
							wordsUpdate.put("activeState",
									activeState.trim());
							
							mydb.update(STORY_TABLE, wordsUpdate, "StoryID ='"
									+ StoryID.trim() + "'", null);
						} else {
							enterWordInfo.put("StoryID", StoryID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo
									.put("story_title", story_title.trim());
							enterWordInfo.put("story_content",
									story_content.trim());
							enterWordInfo.put("other_story_title",
									other_story_title.trim());
							enterWordInfo.put("other_story_content",
									other_story_content.trim());
							enterWordInfo.put("activeState",
									activeState.trim());
							mydb.insert(STORY_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
		}

	}

	public void onBackPressed() {
		super.onBackPressed();
		displayCancelDialog();
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Maori_MainActivity.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_UserLoginActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		builder.show();
	}

	// ***********Memory Handling****************
	@Override
	protected void onStop() {
		super.onStop();
	}

	// Fires after the OnStop() state
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			trimCache(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void trimCache(Context context) {
		try {
			File dir = context.getCacheDir();
			if (dir != null && dir.isDirectory()) {
				deleteDir(dir);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}

	private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... urls) {
			Bitmap map = null;
			for (String url : urls) {
				map = downloadImage(url);
			}
			return map;
		}

		// Sets the Bitmap returned by doInBackground
		@Override
		protected void onPostExecute(Bitmap result) {
			profile_image.setImageBitmap(result);
		}

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
				stream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return bitmap;
		}

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return stream;
		}
	}

	
	
	//***********Camera Image Handling************************
	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else {
			return null;
		}

		return mediaFile;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
	
	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			// videoPreview.setVisibility(View.GONE);
			profile_image.setVisibility(View.VISIBLE);
			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();
			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;
			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			profile_image.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		
		callDialog();
	}
	
	private void callDialog() {
		// TODO Auto-generated method stub
		final Dialog dialog=new Dialog(Maori_MainActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.languageapp_upload_action);
		
		Button uploadaccept=(Button)dialog.findViewById(R.id.uploadimage);
		uploadaccept.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (isNetworkAvailable()) {
					new UploadImageDetails().execute();

				} else {

				}
				dialog.dismiss();
			}
		});
		
		Button uploadreject=(Button)dialog.findViewById(R.id.rejectimage);
		uploadreject.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dialog.dismiss();
			}
		});
		dialog.show();
		
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/************** Uploading Image Details ********************************/
	private class UploadImageDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Maori_MainActivity.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Profile Image");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/saveUserProfileImages.php");
				JSONObject json = new JSONObject();
				json.put("record1", CurrentUID);
				json.put("record2", "http://langapp.mirzabros.com/lanappimage/" + filename);
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("TAG", "IMAGE :" + postjson.toString() + " = " + userMID);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			// mProgressDialog.dismiss();
			new UploadTaskImages().execute();
		}
	}
	
	
	/**************** Uploading Images Via FTP ************************/
	class UploadTaskImages extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			/*
			 * pDialog = new ProgressDialog(Maori_Discover_Word_Details.this);
			 * pDialog.setMessage("Uploading Image Files..."); pDialog.show();
			 */
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + filename);
			Log.v(TAG, "data uploading 3 : " + desDirectoryImage);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectoryImage);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {
						Log.v("", "Upload Success");
					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Maori_MainActivity.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			mProgressDialog.dismiss();
			super.onPostExecute(result);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					Maori_MainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD COMPLETED");
			// Setting Dialog Message
			alertDialog.setMessage("Profile Image Uploaded Successfully...");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					mydb = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE, null);
					ContentValues userUpdate = new ContentValues();
					userUpdate.put("MID", "http://langapp.mirzabros.com/lanappimage/" + filename);
					mydb.update(USER_TABLE, userUpdate,"UID ='" + CurrentUID.trim() + "'", null);		
					mydb.close();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

}
